package com.chaofan.websocket.Web;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.additional.update.impl.LambdaUpdateChainWrapper;
import com.chaofan.websocket.Model.User;
import com.chaofan.websocket.entity.*;
import com.chaofan.websocket.mapper.*;
import com.chaofan.websocket.service.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mysql.cj.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Pattern;

/**
 * Created by Chaofan at 2018/7/4 15:58
 *e mail:chaofan2685@qq.com
 **/
@ServerEndpoint(value = "/websocket")
@Component
public class MyWebSocket {
    private static final Logger logger = LoggerFactory.getLogger(MyWebSocket.class);

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    public  Session session;

    //用以记录用户和房间号的对应关系(sessionId,room)
    private static HashMap<String,String> RoomForUser = new HashMap<String,String>();

    //用以记录房间和其中用户群的对应关系(room,List<用户>)
    public static HashMap<String,CopyOnWriteArraySet<User>> UserForRoom = new HashMap<String,CopyOnWriteArraySet<User>>();

    //用以记录房间和其中用户群的对应关系(room,List<用户>)
    public static HashMap<String,String> PwdForRoom = new HashMap<String,String>();

    //用来存放必应壁纸
    public static List<String> BingImages = new ArrayList<>();

    private Gson gson = new Gson();

    private Random random = new Random();

    private static ApplicationContext applicationContext;

    private static MsgRecordService msgRecordService;

    @Autowired
    public void setOgLocationService(MsgRecordService msgRecordService) {
        MyWebSocket.msgRecordService = msgRecordService;
    }

    private static WeixinUserService weixinUserService;

    @Autowired
    public void setOgLocationService(WeixinUserService weixinUserService) {
        MyWebSocket.weixinUserService = weixinUserService;
    }

    private static PrizeRecordService prizeRecordService;

    @Autowired
    public void setOgLocationService(PrizeRecordService prizeRecordService) {
        MyWebSocket.prizeRecordService = prizeRecordService;
    }

    private static BetRecordService betRecordService;

    @Autowired
    public void setOgLocationService(BetRecordService betRecordService) {
        MyWebSocket.betRecordService = betRecordService;
    }

    private static PrizeRecordMapper prizeRecordMapper;

    @Autowired
    public void setOgLocationService(PrizeRecordMapper prizeRecordMapper) {
        MyWebSocket.prizeRecordMapper = prizeRecordMapper;
    }

    private static WeixinUserMapper weixinUserMapper;

    @Autowired
    public void setOgLocationService(WeixinUserMapper weixinUserMapper) {
        MyWebSocket.weixinUserMapper = weixinUserMapper;
    }

    private static UpdownBranchService updownBranchService;

    @Autowired
    public void setOgLocationService(UpdownBranchService updownBranchService) {
        MyWebSocket.updownBranchService = updownBranchService;
    }

    private static SysUserMapper sysUserMapper;

    @Autowired
    public void setOgLocationService(SysUserMapper sysUserMapper) {
        MyWebSocket.sysUserMapper = sysUserMapper;
    }

    private static LuckyCommandMapper luckyCommandMapper;

    @Autowired
    public void setOgLocationService(LuckyCommandMapper luckyCommandMapper) {
        MyWebSocket.luckyCommandMapper = luckyCommandMapper;
    }

    private static LuckRecordMapper luckRecordMapper;

    @Autowired
    public void setOgLocationService(LuckRecordMapper luckRecordMapper) {
        MyWebSocket.luckRecordMapper = luckRecordMapper;
    }


    private static LuckRecordService luckRecordService;

    @Autowired
    public void setOgLocationService(LuckRecordService luckRecordService) {
        MyWebSocket.luckRecordService = luckRecordService;
    }

    private static UpdownBranchMapper updownBranchMapper;

    @Autowired
    public void setOgLocationService(UpdownBranchMapper updownBranchMapper) {
        MyWebSocket.updownBranchMapper = updownBranchMapper;
    }

    private static UserFlowingMapper userFlowingMapper;

    @Autowired
    public void setOgLocationService(UserFlowingMapper userFlowingMapper) {
        MyWebSocket.userFlowingMapper = userFlowingMapper;
    }

    private static UserFlowingService userFlowingService;

    @Autowired
    public void setOgLocationService(UserFlowingService userFlowingService) {
        MyWebSocket.userFlowingService = userFlowingService;
    }

    private static PumpRecordMapper pumpRecordMapper;

    @Autowired
    public void setOgLocationService(PumpRecordMapper pumpRecordMapper) {
        MyWebSocket.pumpRecordMapper = pumpRecordMapper;
    }

    private static PumpRecordService pumpRecordService;

    @Autowired
    public void setOgLocationService(PumpRecordService pumpRecordService) {
        MyWebSocket.pumpRecordService = pumpRecordService;
    }

    private static AgentInfoService agentInfoService;

    @Autowired
    public void setOgLocationService(AgentInfoService agentInfoService) {
        MyWebSocket.agentInfoService = agentInfoService;
    }

    private static BetRecordMapper betRecordMapper;

    @Autowired
        public void setOgLocationService(BetRecordMapper betRecordMapper) {
        MyWebSocket.betRecordMapper = betRecordMapper;
    }

    /**
     * 连接建立成功调用的方法
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) throws IOException {
        logger.debug("---------------------成功与{}建立连接---------------------",session.getId());
        this.session = session;
        addOnlineCount();
        Map<String,String> result = new HashMap<>();
        result.put("type","bing");
        result.put("msg",BingImages.get(random.nextInt(BingImages.size())));
        result.put("sendUser","系统消息");
        result.put("id",session.getId());
        this.sendMessage(gson.toJson(result));
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        subOnlineCount();
        CopyOnWriteArraySet<User> users = getUsers(session);
        if (users!=null){
            String nick = "某人";
            String weixinId="";
            for (User user : users) {
                if (user.getId().equals(session.getId())){
                    nick = user.getNickname();
                    weixinId = user.getNickname();
                    LambdaQueryWrapper<WeixinUser> wrapper = new LambdaQueryWrapper();
                    wrapper.eq(WeixinUser::getWexinId,weixinId).last("limit 1");
                    WeixinUser weixinUser = weixinUserService.getOne(wrapper);
                    nick =weixinUser.getWexinName();
                }
            }
//            Map<String,String> result = new HashMap<>();
//            result.put("type","init");
//            result.put("msg",nick+"离开房间");
//            result.put("sendUser","系统消息");
            User closeUser = getUser(session);
            users.remove(closeUser);
            if (users.size() == 0){
                String room = RoomForUser.get(session.getId());
                UserForRoom.remove(room);
                PwdForRoom.remove(room);
            }
            RoomForUser.remove(session.getId());

//            if(users !=null){
//                sendRoomMessagesOther(users,gson.toJson(result));
//            }
        }
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 消息内容
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        Map<String,String> map = new Gson().fromJson(message, new TypeToken<HashMap<String,String>>(){}.getType());
        Map<String,String> result = new HashMap<>();
        MsgRecord msgRecord = new MsgRecord();
        WeixinUser weChatUserOne=new WeixinUser();
        if (map.get("type").equals("msg") || map.get("type").equals("img")) {
            LambdaQueryWrapper<WeixinUser> wrapperOne = new LambdaQueryWrapper();
            wrapperOne.eq(WeixinUser::getWexinId, getUser(session).getNickname())
                    .eq(WeixinUser::getRoom, RoomForUser.get(session.getId())).select();
            weChatUserOne= weixinUserService.getOne(wrapperOne);
        }
        String shiels = map.containsKey("shiels")?map.get("shiels").toString():null;
        switch (map.get("type")){
            case "msg" :
                User user = null;
                user = getUser(session);
                result.put("type","msg");
                result.put("msg",map.get("msg"));
                result.put("sendUser",weChatUserOne.getWexinName());
                result.put("image",weChatUserOne.getImage());
                result.put("shake",map.get("shake"));
                msgRecord.setType(1);

                break;
            case "init":
                String room = map.get("room");
                String nick = map.get("nick");
                String pwd = map.get("pwd");
                String weixinId = map.get("weixinId");
                QueryWrapper<WeixinUser> queryWrapperSdf = new QueryWrapper<>();
                queryWrapperSdf.lambda().eq(WeixinUser::getWexinId,weixinId).eq(WeixinUser::getRoom,room);
                WeixinUser weixinUser = weixinUserMapper.selectOne(queryWrapperSdf);
                QueryWrapper<SysUser> sysUserWrapper = new QueryWrapper<>();
                sysUserWrapper.lambda().eq(SysUser::getRoom,room);
                SysUser sysUser = sysUserMapper.selectOne(sysUserWrapper);
                if(weixinUser.getIsFlag()==0 && sysUser.getStatus().equals("0") && sysUser.getRoom()!=null){
                    if (room != null && nick != null){
                        user = new User(session.getId(),weixinId,this);
                        //如果房间不存在，新建房间
                        if (UserForRoom.get(room) == null){
                            CopyOnWriteArraySet<User> roomUsers = new CopyOnWriteArraySet<>();
                            roomUsers.add(user);
                            UserForRoom.put(room, roomUsers);
                            RoomForUser.put(session.getId(), room);
    //                        if (StrUtil.isNotEmpty(pwd)){
    //                            PwdForRoom.put(room,pwd);
    //                        }
                        }else {
                            UserForRoom.get(room).add(user);
                            RoomForUser.put(session.getId(),room);
    //                        for (User userInfo: UserForRoom.get(room)) {
    //                            if (!userInfo.getNickname().equals(user.getNickname())) {
    //                                UserForRoom.get(room).add(user);
    //                                RoomForUser.put(session.getId(),room);
    //                            }else{
    //                                UserForRoom.remove(RoomForUser.get(session.getId()));
    //                                RoomForUser.put(session.getId(),room);
    //                            }
    //                        }
                        }
//                        result.put("type","init");
//                        result.put("msg",nick+"成功加入房间");
//                        result.put("sendUser","系统消息");
                    }
                }
                break;
            case "img":
                user = getUser(session);
                result.put("type","img");
                result.put("msg",map.get("msg"));
                result.put("sendUser",weChatUserOne.getWexinName());
                msgRecord.setType(2);
                break;
            case "ping":
                return;
        }
        if (map.get("type").equals("msg") || map.get("type").equals("img")) {

            msgRecord.setMsg(map.get("msg"));
            msgRecord.setRoomId(RoomForUser.get(session.getId()));
            msgRecord.setUserId( weChatUserOne.getId());
            msgRecord.setWexinName(weChatUserOne.getWexinName());
            msgRecord.setWexinId(getUser(session).getNickname());
            msgRecord.setCreateTime(DateUtil.date());
            msgRecordService.save(msgRecord);
        }
        if (StrUtil.isEmpty(shiels)){
//            sendMessagesAll(UserForRoom.get(RoomForUser.get(session.getId())),gson.toJson(result));
            if (getUsers(session)!=null) {
                sendRoomMessagesOther(getUsers(session), gson.toJson(result));
            }
        }else {
//            sendMessagesAll(UserForRoom.get(RoomForUser.get(session.getId())),gson.toJson(result),shiels);
            if (getUsers(session)!=null) {
                sendRoomMessagesOther(getUsers(session), gson.toJson(result));
            }
        }
        if (map!=null && !StringUtils.isNullOrEmpty(map.get("msg"))  ) {
            rootSendMessage(map.get("msg"),weChatUserOne.getWexinName());
        }
    }

    public HashMap luckSendMessage(String msg,String userName){
        HashMap<String, Object> result = new HashMap<>();
        boolean state = true;
        MsgRecord msgRecord = new MsgRecord();
        msgRecord.setRoomId(RoomForUser.get(session.getId()));
        msgRecord.setWexinName("机器人");
        msgRecord.setCreateTime(DateUtil.date());
        msgRecord.setType(1);
        String startStr = "";
        String middleStr = "";
        String sendMsg = "";
        String endStr = "";
        int startNum = 0;
        Double endNum = 0.00;
        Integer type=0;
        String regx="";
        LambdaQueryWrapper<PrizeRecord> wrapperPrizeRecord = new LambdaQueryWrapper();
        wrapperPrizeRecord.eq(PrizeRecord::getState, 1).isNotNull(PrizeRecord::getPrizeTime).select();
        PrizeRecord prizeRecordOne = prizeRecordService.getOne(wrapperPrizeRecord);
        List<LuckyCommand> luckyCommandList = luckyCommandMapper.getLuckyCommandList();
        //^(?:([1-4])){1}(?:([1-4])(?<!\1)){1}(/)(?:([1-4])(?<!\1)(?<!\2)){1}
        if (!msg.equals("余额") && !msg.equals("查") && !msg.contains("上分") && !msg.contains("下分") && !msg.contains("上") && !msg.contains("下") && !msg.contains("流水") && !msg.equals("撤单")) {
            try {
                for (LuckyCommand luck:luckyCommandList) {

                    if ((luck.getCommand().contains("番") || luck.getCommand().contains("翻") || luck.getCommand().contains("花")
                            || luck.getCommand().contains("番头")) &  (msg.contains("番") || msg.contains("翻")
                            || msg.contains("花") || msg.contains("番头"))) {
                        //1. 番、翻、花、番头
                        regx="^(([1-4]))([番,翻,花,番头])((?:[1-9][0-9]{0,11}))$";
                        boolean regexState = getRegex(regx, msg);
                        if (regexState) {
                            type=1;
                            break;
                        }

                    }else if ((luck.getCommand().contains("角") || luck.getCommand().contains("架桥") ) &
                            (msg.contains("角")  || msg.contains("架桥"))) {
                        //2. 角、架桥
                        regx="^([1-4])(?!\\1)([1-4])([角,架桥])((?:[1-9][0-9]{0,11}))$";
                        boolean regexState = getRegex(regx, msg);
                        if (regexState) {
                            type=2;
                            break;
                        }
                    }else if ((luck.getCommand().contains("车") || luck.getCommand().contains("推车") || luck.getCommand().contains("挨车")
                            || luck.getCommand().contains("三门")) &  (msg.contains("车") || msg.contains("推车")
                            || msg.contains("挨车") || msg.contains("三门"))) {
                        //3. 车、推车、挨车、三门
//                        regx="^((123)|(234)|(124)|(134))((车)|(推车)|(挨车)|(三门))((?:[1-9][0-9]{0,11}))$";
                        regx="^([1-4])((车)|(推车)|(挨车)|(三门))((?:[1-9][0-9]{0,11}))$";
                        boolean regexState = getRegex(regx, msg);
                        if (regexState) {
                            type=3;
                            break;
                        }
                    }else if ((luck.getCommand().contains("念") || luck.getCommand().contains("严") || luck.getCommand().contains("粘")
                            || luck.getCommand().contains("念头")) &  (msg.contains("念") || msg.contains("严")
                            || msg.contains("粘") || msg.contains("念头"))) {
                        //4. 念、严、粘、念头
                        regx="^([1-4])((念头)|(念)|(严)|(粘))(?!\\1)([1-4])/((?:[1-9][0-9]\\d*))$";
                        boolean regexState = getRegex(regx, msg);
                        if (regexState) {
                            type=4;
                            break;
                        }else {
                            //5. 加念
                            regx="^([1-4])(念)(?!\\1)([1-4])(?!\\1|\\3)([1-4])/((?:[1-9][0-9]\\d*))$";
                            regexState = getRegex(regx, msg);
                            if (regexState) {
                                type=5;
                                break;
                            }
                        }
                    } else if ((luck.getCommand().contains("堂") || luck.getCommand().contains("唐") || luck.getCommand().contains("正")
                            || luck.getCommand().contains("堂头")) &  (msg.contains("堂") || msg.contains("唐")
                            || msg.contains("正") || msg.contains("堂头"))) {
                        //6. 堂、唐、正、堂头
                        regx="^(([1-4]))([堂,唐,正,堂头])((?:[1-9][0-9]{0,11}))$";
                        boolean regexState = getRegex(regx, msg);
                        if (regexState) {
                            type=6;
                            break;
                        }
                    }else if ((luck.getCommand().contains("通")) &
                            (msg.contains("通"))) {
                        //7. 通
                        regx="^([1-4])(通)(?!\\1)([1-4])(?!\\1|\\3)([1-4])/((?:[1-9][0-9]\\d*))$";
//                        regx="^(?:([1-4])){1}(通)(?:([1-4])(?<!\\1)){1}(?:([1-4])(?<!\\1)(?<!\\3)){1}(/)((?:[1-9][0-9]{0,11}))$";
                        boolean regexState = getRegex(regx, msg);
                        if (regexState) {
                            type=7;
                            break;
                        }
                    }else if ((luck.getCommand().contains("单") || luck.getCommand().contains("双") ) &
                            (msg.contains("单")  || msg.contains("双"))) {
                        //8. 单、双
                        regx="^((单)|(双))((?:[1-9][0-9]{0,11}))$";
                        boolean regexState = getRegex(regx, msg);
                        if (regexState) {
                            type=8;
                            break;
                        }
                    }else if ((luck.getCommand().contains("大") || luck.getCommand().contains("小") ) &
                            (msg.contains("大")  || msg.contains("小"))) {
                        //9. 大、小
                        regx="^((大)|(小))((?:[1-9][0-9]{0,11}))$";
                        boolean regexState = getRegex(regx, msg);
                        if (regexState) {
                            type=9;
                            break;
                        }
                    }else if ((luck.getCommand().contains("特码")) &
                            (msg.contains("特") || msg.contains("特码"))) {
                        //10. 特码
                        boolean regexState =getEspecial(msg);
                        if (regexState) {
                            type=10;
                            break;
                        }
                    }else {
                        regx="^([1-4])(?!\\1)([1-4])/((?:[1-9][0-9]{0,11}))$";
                        boolean regexState = getRegex(regx, msg);
                        if (regexState) {
                            type=11;
                            break;
                        }else {
                            regx="^([1-4])(\\+)(?!\\1)([1-4])/((?:[1-9][0-9]\\d*))$";
                            regexState = getRegex(regx, msg);
                            if (regexState) {
                                type=12;
                                break;
                            }else {

                                    regx="^([1-4])/((?:[1-9][0-9]\\d*))$";
                                    regexState = getRegex(regx, msg);
                                    if (regexState) {
                                        type=13;
                                        break;
                                    }else{
                                        regx="^([1-4])(\\+)(?!\\1)([1-4])(?!\\1|\\3)([1-4])/((?:[1-9][0-9]\\d*))$";
                                        regexState = getRegex(regx, msg);
                                        if (regexState) {
                                            type=14;
                                            break;
                                        }else{
                                            regx="^([1-4])(?!\\1)([1-4])(-)(?!\\1|\\2)([1-4])/((?:[1-9][0-9]\\d*))$";
                                            regexState = getRegex(regx, msg);
                                            if (regexState) {
                                                type=15;
                                                break;
                                            }else{
                                                regx="^([1-4])(-)(?!\\1)([1-4])/((?:[1-9][0-9]\\d*))$";
                                                regexState = getRegex(regx, msg);
                                                if (regexState) {
                                                    type=16;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                            }
                        }
                    }
                    logger.info("type:"+type);
                }
//                startStr = substring(msg, 0, 1);
//                middleStr = substring(msg, 1, 2);
//                endStr = substring(msg, 2);
//                startNum = Integer.valueOf(startStr).intValue();
//                endNum = Double.valueOf(endStr);
                if (type==0) {
                    msg = "@" + userName + " 指令输入有误";
                }
            } catch (Exception e) {
                System.out.println(e);
                type=0;
                msg = "@" + userName + " 指令输入有误";
                state = false;
            }
        }
        result.put("sendMsg",msg);
        result.put("type",type);
        return result;
    }

    //正则表达式
    public static boolean getRegex(String regx,String msg){
        Pattern pattern = Pattern.compile(regx);
        boolean matcher = pattern.matcher(msg).find();

        return matcher;
    }

    //校验特码的规则
    public static boolean getEspecial(String msg){
        boolean state=false;
        HashMap<String, Object> numMap = new HashMap<>();
        for (Integer i=1;i<=20;i++) {
            String b=i<10?"0"+i:i.toString();
            numMap.put(b,1);
        }
        int i=-1;
        int i1 = msg.indexOf("特");
        int i2=msg.indexOf("特码");
        if (i1==-1 && i2==-1) {
            return state;
        }
        if (i1>0) {
            i=i1;
        }else {
            i=i2;
        }
        int length = msg.length();
        String substring = msg.substring(0, i);
        String end = msg.substring(i, length);
        String[] split = substring.split("/");
        HashMap<String, String> map = new HashMap<>();

        for (String b:split){
            if (numMap.get(b)==null) {
                break;
            }
            map.put(b,"");
            if (map.size()==split.length && split.length<=20) {
                state=true;
            }
        }
        System.out.println("i:"+i+",s:"+length+",string:"+substring+",end"+end.replaceAll("(特码)|(特)",""));
        return state;
    }

    public static void main(String[] args) {
//        int startNum=0;
//        String luck="01/02/03/04/05/06/07/08/09/10/11/12/13/14/15/16/17/18/19/20特100";
//        startNum= luck.indexOf("特");
//        System.out.println(DateUtil.date());
//
//        String strOne=luck.substring(startNum,luck.length());
//        String regx="";
//        String msg="4堂300";
//        regx="^(([1-4]))([堂,唐,正,堂头])((?:[1-9][0-9]{0,11}))$";
//        boolean regexState = getRegex(regx, msg);
//        String luck="01/02/03/04/05/06/07/08/09/10/11/12/13/14/15/16/17/18/19/20特100";
//        String luckOne="01/02特100";
//        String luckTne="01特100";
//        System.out.println(luck.split("/").length+" "+luckTne.split("/").length+" "+luckOne.split("/").length);
        System.out.println("fwwww".substring(0,1));
    }




    public void rootSendMessage(String msg,String userName){
        Map<String,String> rootResult = new HashMap<>();
        LambdaQueryWrapper<AgentInfo> wrapperAgentInfoOne = new LambdaQueryWrapper();
        String thisRoom = RoomForUser.get(session.getId());

        wrapperAgentInfoOne.eq(AgentInfo::getRoom,thisRoom).select();
        AgentInfo agentInfoOne = agentInfoService.getOne(wrapperAgentInfoOne);
        Integer agentType = agentInfoOne.getAgentType();
        boolean state = true;

        String startStr = "";
        String middleStr = "";

        String endStr = "";
        int startNum = 0;
        Double endNum = 0.00;
        int length = msg.split("，").length;
        if (agentInfoOne.getAgentState()==1) {
            MsgRecord msgRecord = new MsgRecord();
            msgRecord.setRoomId(RoomForUser.get(session.getId()));
            msgRecord.setWexinName("机器人");
            msgRecord.setCreateTime(DateUtil.date());
            msgRecord.setType(1);
            String sendMsg = "";
            int type = 0;

            LambdaQueryWrapper<WeixinUser> wrapper = new LambdaQueryWrapper();
            wrapper.eq(WeixinUser::getWexinId, getUser(session).getNickname())
                    .eq(WeixinUser::getRoom, RoomForUser.get(session.getId())).select();
            WeixinUser weixinUser = weixinUserService.getOne(wrapper);
            if (agentType==2 && length==1) {
                LambdaQueryWrapper<PrizeRecord> wrapperPrizeRecord = new LambdaQueryWrapper();
                wrapperPrizeRecord.eq(PrizeRecord::getState, 1).isNotNull(PrizeRecord::getPrizeTime).select();
                PrizeRecord prizeRecordOne = prizeRecordService.getOne(wrapperPrizeRecord);
                HashMap hashMap = luckSendMessage(msg, userName);
                sendMsg=hashMap.get("sendMsg").toString();
                type=Integer.valueOf(hashMap.get("type").toString());
                String command="";
                String littleCommand ="";
                try {
                    if (type==1) {

                        if (sendMsg.contains("番头")){
                            command="番头";
                            startNum= sendMsg.indexOf("番头");
                        }else if(sendMsg.contains("番")){
                            command="番";
                            startNum= sendMsg.indexOf("番");
                        }else if(sendMsg.contains("翻")){
                            command="翻";
                            startNum= sendMsg.indexOf("翻");
                        }else if(sendMsg.contains("花")){
                            command="花";
                            startNum= sendMsg.indexOf("花");
                        }
                    }else if(type==2){
                        if (sendMsg.contains("角")){
                            command="角";
                            startNum= sendMsg.indexOf("角");
                        }else if(sendMsg.contains("架桥")){
                            command="架桥";
                            startNum= sendMsg.indexOf("架桥");
                        }
                    }else if(type==3){
                        if (sendMsg.contains("推车")){
                            command="推车";
                            startNum= sendMsg.indexOf("推车");
                        }else if(sendMsg.contains("挨车")){
                            command="挨车";
                            startNum= sendMsg.indexOf("挨车");
                        }else if(sendMsg.contains("三门")){
                            command="三门";
                            startNum= sendMsg.indexOf("三门");
                        }else if(sendMsg.contains("车")){
                            command="车";
                            startNum= sendMsg.indexOf("车");
                        }
                    }else if(type==4){
                        if (sendMsg.contains("念头")){
                            command="念头";
                            startNum= sendMsg.indexOf("念头");
                        }else if(sendMsg.contains("念")){
                            command="念";
                            startNum= sendMsg.indexOf("念");
                        }else if(sendMsg.contains("严")){
                            command="严";
                            startNum= sendMsg.indexOf("严");
                        }else if(sendMsg.contains("粘")){
                            command="粘";
                            startNum= sendMsg.indexOf("粘");
                        }
                    }else if(type==5){
                        if (sendMsg.contains("念")){
                            command="念";
                            startNum= sendMsg.indexOf("念");
                        }
                    }else if(type==6){
                        if (sendMsg.contains("堂头")){
                            command="堂头";
                            startNum= sendMsg.indexOf("堂头");
                        }else if(sendMsg.contains("堂")){
                            command="堂";
                            startNum= sendMsg.indexOf("堂");
                        }else if(sendMsg.contains("唐")){
                            command="唐";
                            startNum= sendMsg.indexOf("唐");
                        }else if(sendMsg.contains("正")){
                            command="正";
                            startNum= sendMsg.indexOf("正");
                        }
                    }else if(type==7){
                        if (sendMsg.contains("通")){
                            command="通";
                            startNum= sendMsg.indexOf("通");
                        }
                    }else if(type==8){
                        if (sendMsg.contains("单")){
                            command="单";
                            startNum= sendMsg.indexOf("单");
                        }else if(sendMsg.contains("双")){
                            command="双";
                            startNum= sendMsg.indexOf("双");
                        }
                    }else if(type==9){
                        if (sendMsg.contains("大")){
                            command="大";
                            startNum= sendMsg.indexOf("大");
                        }else if(sendMsg.contains("小")){
                            command="小";
                            startNum= sendMsg.indexOf("小");
                        }
                    }else if(type==10){
                        if (sendMsg.contains("特")){
                            command="特";
                            startNum= sendMsg.indexOf("特");

                        }
                    }


                    //
                    if (type!=4 && type!=5 && type!=7 && type<=10) {
                        String strOne=sendMsg.substring(startNum,sendMsg.length());
                        String str = strOne.replaceAll(command, "");

                        if (type==10) {
                            endNum = Double.valueOf(str);
                            endNum=endNum*(sendMsg.split("/").length);
                            littleCommand = sendMsg.substring(0, startNum+1);
                        }else{
                            littleCommand = sendMsg.substring(0, startNum+1);
                            endNum = Double.valueOf(str);
                        }
                    }else {
                        command="/";
                        startNum= sendMsg.indexOf(command);
                        String strOne=sendMsg.substring(startNum,sendMsg.length());
                        String str = strOne.replaceAll(command, "");
                        littleCommand = sendMsg.substring(0, sendMsg.indexOf("/"));
                        endNum = Double.valueOf(str);
                    }
                    logger.info(littleCommand);
                } catch (Exception e) {
                    sendMsg = "@" + userName + " 指令输入有误";
                    state = false;
                }
                if(state){
                    if (endNum>0 && endNum>=10) {
                        //抽水金额多位小数
                        //代理抽水金额
                        endNum= new Double(String.format("%.2f",endNum));
                        String room=weixinUser.getRoom()+"";
                        String wexinId = weixinUser.getWexinId();
                        Double price = Double.valueOf(weixinUser.getPrice());
                        if (endNum<=price) {
                            if (prizeRecordOne.getSealingState()==2) {
                                sendMsg="@"+userName+" "+msg +" 已封盘，请稍后再试";
                            }else {
                                LambdaQueryWrapper<AgentInfo> wrapperAgentInfo = new LambdaQueryWrapper();
                                wrapperAgentInfo.eq(AgentInfo::getRoom,room).select();
                                AgentInfo agentInfo = agentInfoService.getOne(wrapperAgentInfo);
                                LambdaQueryWrapper<PumpRecord> wrapperPumpRecord = new LambdaQueryWrapper();
                                wrapperPumpRecord.eq(PumpRecord::getRoom,room)
                                        .eq(PumpRecord::getPeriod,prizeRecordOne.getPeriod()).select();
                                PumpRecord pumpRecordInfo = pumpRecordService.getOne(wrapperPumpRecord);
                                if (prizeRecordOne != null) {
                                    //下注记录
                                    Long userId = weixinUser.getId();
                                    String wexinName = weixinUser.getWexinName();
                                    Double remainPrice = price - endNum;
                                    BetRecord betRecord = new BetRecord();
                                    betRecord.setCommand(msg);
                                    betRecord.setCreateTime(DateUtil.date());
                                    betRecord.setPeriod(prizeRecordOne.getPeriod());
                                    betRecord.setPayPrice(endNum);
                                    betRecord.setRoom(room);
                                    betRecord.setLittleCommand(littleCommand);
                                    betRecord.setUserId(userId);
                                    betRecord.setPayNum(startNum);
                                    betRecord.setWexinId(wexinId);
                                    betRecord.setWexinName(wexinName);
                                    betRecordService.save(betRecord);

                                    //期数奖金池金额修改
                                    LambdaUpdateChainWrapper<PrizeRecord> lambdaUpdateChainWrapper = new LambdaUpdateChainWrapper<>(prizeRecordMapper);
                                    boolean update = lambdaUpdateChainWrapper.eq(PrizeRecord::getRecordId, prizeRecordOne.getRecordId())
                                            .set(PrizeRecord::getJackpotPrice, prizeRecordOne.getJackpotPrice() + endNum)
                                            .set(PrizeRecord::getRemainingPrice, prizeRecordOne.getJackpotPrice() + endNum)
                                            .set(PrizeRecord::getUpdateTime, DateUtil.date()).update();

                                    //记录用户流水
                                    UserFlowing userFlowing = new UserFlowing();
                                    userFlowing.setCreateTime(DateUtil.date());
                                    userFlowing.setUserId(userId);
                                    userFlowing.setWexinId(wexinId);
                                    userFlowing.setWexinName(wexinName);
                                    userFlowing.setRoom(room);
                                    userFlowing.setPeriod(prizeRecordOne.getPeriod());
                                    userFlowing.setPayType(1);
                                    userFlowing.setIsFlowing(1);
                                    userFlowing.setBetId(betRecord.getId());
                                    userFlowing.setStartPrice(new BigDecimal(price));
                                    userFlowing.setPayPrice(new BigDecimal(endNum));
                                    userFlowing.setEndPrice(new BigDecimal(remainPrice));
                                    userFlowing.setRemark("用户下注");
                                    userFlowingService.save(userFlowing);

                                    if (pumpRecordInfo == null) {
                                        //记录代理盘投入的总金额
                                        PumpRecord pumpRecord = new PumpRecord();
                                        pumpRecord.setCreateTime(DateUtil.date());
                                        pumpRecord.setAgentId(agentInfo.getId());
                                        pumpRecord.setAgentName(agentInfo.getAgentName());
                                        pumpRecord.setPeriod(prizeRecordOne.getPeriod());
                                        pumpRecord.setRoom(room);
                                        pumpRecord.setSumPrice(new BigDecimal(endNum));
                                        pumpRecordService.save(pumpRecord);
                                    } else {
                                        LambdaUpdateChainWrapper<PumpRecord> lambdaUpdatePumpRecord = new LambdaUpdateChainWrapper<>(pumpRecordMapper);
                                        lambdaUpdatePumpRecord.eq(PumpRecord::getPeriod, prizeRecordOne.getPeriod())
                                                .eq(PumpRecord::getRoom, room)
                                                .set(PumpRecord::getSumPrice, pumpRecordInfo.getSumPrice().add(new BigDecimal(endNum)))
                                                .set(PumpRecord::getUpdateTime, DateUtil.date()).update();
                                    }

                                    //修改用户余额
                                    LambdaUpdateChainWrapper<WeixinUser> lambdaUpdateUserWrapper = new LambdaUpdateChainWrapper<>(weixinUserMapper);
                                    lambdaUpdateUserWrapper.eq(WeixinUser::getId, userId)
                                            .set(WeixinUser::getUpdateTime, DateUtil.date())
                                            .set(WeixinUser::getPrice, remainPrice).update();
                                    remainPrice = new Double(String.format("%.2f", remainPrice));
                                    sendMsg = "@" + userName + " 用" + endNum + " 剩" + remainPrice +" 粮草";

                                } else {
                                    sendMsg = "@" + userName + " 请稍等";
                                }
                            }
                        }else{
                            sendMsg="@"+userName+" 粮草不足";
                        }
                    }else if (endNum>0 && endNum<10){
                        sendMsg = "@" + userName + " 投注金额必须十元起步";
                    } else {
                        sendMsg="@"+userName+" 指令输入有误";
                    }

                }else if (msg.equals("撤单")) {
                    //上期时间+30秒
                    PrizeRecord maxPrizeRecordByPrizeTime = prizeRecordMapper.getMaxPrizeRecordByPrizeTime();
                    DateTime dateTime = DateUtil.offsetSecond(maxPrizeRecordByPrizeTime.getPrizeTime(), 30);
                    if (dateTime.getTime() > DateUtil.date().getTime() && DateUtil.date().getTime() <= maxPrizeRecordByPrizeTime.getPrizeTime().getTime()) {
                        BetRecord betRecord = new BetRecord();
                        betRecord.setWexinId(getUser(session).getNickname());
                        betRecord.setRoom(RoomForUser.get(session.getId()));
                        betRecord.setPeriod(prizeRecordOne.getPeriod());
                        //返回用户所有投注的金额
                        Double userAllBetRecordPrice = betRecordMapper.getUserAllBetRecordPrice(betRecord);
                        if (userAllBetRecordPrice != 0 && userAllBetRecordPrice != null) {
                            //查询用户信息

                            //修改用户余额
                            LambdaUpdateChainWrapper<WeixinUser> lambdaUpdateUserWrapper = new LambdaUpdateChainWrapper<>(weixinUserMapper);
                            lambdaUpdateUserWrapper.eq(WeixinUser::getId, weixinUser.getId())
                                    .set(WeixinUser::getUpdateTime, DateUtil.date())
                                    .set(WeixinUser::getPrice, weixinUser.getPrice() + userAllBetRecordPrice).update();

                            //删除用户投注记录
                            Long[] ids = betRecordMapper.getUserAllBetRecord(betRecord);
                            if (ids.length != 0) {
                                for (Long id : ids) {
                                    betRecordMapper.deleteThePeriodAllBetRecord(id);
                                }
                            }
                            //删除该期用户流水
                            UserFlowing userFlowing = new UserFlowing();
                            userFlowing.setWexinId(getUser(session).getNickname());
                            userFlowing.setRoom(RoomForUser.get(session.getId()));
                            userFlowing.setPeriod(prizeRecordOne.getPeriod());
                            userFlowingMapper.deleteAllFlowingForUser(userFlowing);

                            sendMsg = "@" + userName + " 撤单成功";
                        } else {
                            sendMsg = "@" + userName + " \"" + msg + "\" 指令无效,请在规定时间里下单";
                        }
                    } else {
                        sendMsg = "@" + userName + " \"" + msg + "\"不在时间范围内";
                    }
                }

            }else if(agentType==2 && length>1){
                LambdaQueryWrapper<PrizeRecord> wrapperPrizeRecord = new LambdaQueryWrapper();
                wrapperPrizeRecord.eq(PrizeRecord::getState, 1).isNotNull(PrizeRecord::getPrizeTime).select();
                PrizeRecord prizeRecordOne = prizeRecordService.getOne(wrapperPrizeRecord);
                String[] split = msg.split("，");
                List<HashMap> hashMapList = new ArrayList<>();
                for (String s:split) {
                    HashMap betMap=new HashMap();
                    HashMap hashMap = luckSendMessage(s, userName);
                    sendMsg=hashMap.get("sendMsg").toString();
                    type=Integer.valueOf(hashMap.get("type").toString());
                    if (type==0) {
                        sendMsg = "@" + userName + " 指令输入有误";
                        state = false;
                        break;
                    }
                    String command="";
                    String littleCommand ="";
                    try {
                        if (type==1) {

                            if (sendMsg.contains("番头")){
                                command="番头";
                                startNum= sendMsg.indexOf("番头");
                            }else if(sendMsg.contains("番")){
                                command="番";
                                startNum= sendMsg.indexOf("番");
                            }else if(sendMsg.contains("翻")){
                                command="翻";
                                startNum= sendMsg.indexOf("翻");
                            }else if(sendMsg.contains("花")){
                                command="花";
                                startNum= sendMsg.indexOf("花");
                            }
                        }else if(type==2){
                            if (sendMsg.contains("角")){
                                command="角";
                                startNum= sendMsg.indexOf("角");
                            }else if(sendMsg.contains("架桥")){
                                command="架桥";
                                startNum= sendMsg.indexOf("架桥");
                            }
                        }else if(type==3){
                            if (sendMsg.contains("推车")){
                                command="推车";
                                startNum= sendMsg.indexOf("推车");
                            }else if(sendMsg.contains("挨车")){
                                command="挨车";
                                startNum= sendMsg.indexOf("挨车");
                            }else if(sendMsg.contains("三门")){
                                command="三门";
                                startNum= sendMsg.indexOf("三门");
                            }else if(sendMsg.contains("车")){
                                command="车";
                                startNum= sendMsg.indexOf("车");
                            }
                        }else if(type==4){
                            if (sendMsg.contains("念头")){
                                command="念头";
                                startNum= sendMsg.indexOf("念头");
                            }else if(sendMsg.contains("念")){
                                command="念";
                                startNum= sendMsg.indexOf("念");
                            }else if(sendMsg.contains("严")){
                                command="严";
                                startNum= sendMsg.indexOf("严");
                            }else if(sendMsg.contains("粘")){
                                command="粘";
                                startNum= sendMsg.indexOf("粘");
                            }
                        }else if(type==5){
                            if (sendMsg.contains("念")){
                                command="念";
                                startNum= sendMsg.indexOf("念");
                            }
                        }else if(type==6){
                            if (sendMsg.contains("堂头")){
                                command="堂头";
                                startNum= sendMsg.indexOf("堂头");
                            }else if(sendMsg.contains("堂")){
                                command="堂";
                                startNum= sendMsg.indexOf("堂");
                            }else if(sendMsg.contains("唐")){
                                command="唐";
                                startNum= sendMsg.indexOf("唐");
                            }else if(sendMsg.contains("正")){
                                command="正";
                                startNum= sendMsg.indexOf("正");
                            }
                        }else if(type==7){
                            if (sendMsg.contains("通")){
                                command="通";
                                startNum= sendMsg.indexOf("通");
                            }
                        }else if(type==8){
                            if (sendMsg.contains("单")){
                                command="单";
                                startNum= sendMsg.indexOf("单");
                            }else if(sendMsg.contains("双")){
                                command="双";
                                startNum= sendMsg.indexOf("双");
                            }
                        }else if(type==9){
                            if (sendMsg.contains("大")){
                                command="大";
                                startNum= sendMsg.indexOf("大");
                            }else if(sendMsg.contains("小")){
                                command="小";
                                startNum= sendMsg.indexOf("小");
                            }
                        }else if(type==10){
                            if (sendMsg.contains("特")){
                                command="特";
                                startNum= sendMsg.indexOf("特");

                            }
                        }
                        betMap.put("startNum",startNum);
                        //
                        if (type!=4 && type!=5 && type!=7 && type<=10) {
                            String strOne=sendMsg.substring(startNum,sendMsg.length());
                            String str = strOne.replaceAll(command, "");

                            if (type==10) {
                                Double price = Double.valueOf(str);
                                betMap.put("endNum",price);
                                littleCommand = sendMsg.substring(0, startNum+1);
                                endNum+=price*(sendMsg.split("/").length);
                            }else{
                                endNum += Double.valueOf(str);
                                littleCommand = sendMsg.substring(0, startNum+1);
                                betMap.put("endNum", Double.valueOf(str));
                            }
                        }else {
                            command="/";
                            startNum= sendMsg.indexOf(command);
                            String strOne=sendMsg.substring(startNum,sendMsg.length());
                            String str = strOne.replaceAll(command, "");
                            littleCommand = sendMsg.substring(0, sendMsg.indexOf("/"));
                            endNum += Double.valueOf(str);
                            betMap.put("endNum",Double.valueOf(str));
                        }
                        betMap.put("msg",s);
                        betMap.put("littleCommand",littleCommand);
                        hashMapList.add(betMap);
                    } catch (Exception e) {
                        sendMsg = "@" + userName + " 指令输入有误";
                        state = false;
                    }
                }
                if(state){
                    if (endNum>0 && endNum>=10) {
                        //抽水金额多位小数
                        //代理抽水金额
                        endNum= new Double(String.format("%.2f",endNum));
                        String room=weixinUser.getRoom()+"";
                        String wexinId = weixinUser.getWexinId();
                        Double price = Double.valueOf(weixinUser.getPrice());
                        if (endNum<=price) {
                            if (prizeRecordOne.getSealingState()==2) {
                                sendMsg="@"+userName+" "+msg +" 已封盘，请稍后再试";
                            }else {
                                LambdaQueryWrapper<AgentInfo> wrapperAgentInfo = new LambdaQueryWrapper();
                                wrapperAgentInfo.eq(AgentInfo::getRoom,room).select();
                                AgentInfo agentInfo = agentInfoService.getOne(wrapperAgentInfo);
                                LambdaQueryWrapper<PumpRecord> wrapperPumpRecord = new LambdaQueryWrapper();
                                wrapperPumpRecord.eq(PumpRecord::getRoom,room)
                                        .eq(PumpRecord::getPeriod,prizeRecordOne.getPeriod()).select();
                                PumpRecord pumpRecordInfo = pumpRecordService.getOne(wrapperPumpRecord);
                                if (prizeRecordOne != null) {
                                    //下注记录
                                    Long userId = weixinUser.getId();
                                    String wexinName = weixinUser.getWexinName();
                                    Double remainPrice = price - endNum;

                                    Double newPrice = price;
                                    for (HashMap map:hashMapList) {
                                        BetRecord betRecord = new BetRecord();
                                        betRecord.setCommand(map.get("msg").toString());
                                        betRecord.setCreateTime(DateUtil.date());
                                        betRecord.setPeriod(prizeRecordOne.getPeriod());
                                        betRecord.setPayPrice(new Double(map.get("endNum").toString()));
                                        betRecord.setRoom(room);
                                        betRecord.setUserId(userId);
                                        betRecord.setPayNum(Integer.valueOf(map.get("startNum").toString()));
                                        betRecord.setWexinId(wexinId);
                                        betRecord.setWexinName(wexinName);
                                        betRecord.setLittleCommand(map.get("littleCommand").toString());

                                        betRecordService.save(betRecord);


                                        //记录用户流水
                                        UserFlowing userFlowing = new UserFlowing();
                                        userFlowing.setCreateTime(DateUtil.date());
                                        userFlowing.setUserId(userId);
                                        userFlowing.setWexinId(wexinId);
                                        userFlowing.setWexinName(wexinName);
                                        userFlowing.setRoom(room);
                                        userFlowing.setPeriod(prizeRecordOne.getPeriod());
                                        userFlowing.setPayType(1);
                                        userFlowing.setIsFlowing(1);
                                        userFlowing.setBetId(betRecord.getId());
                                        userFlowing.setStartPrice(new BigDecimal(newPrice));
                                        userFlowing.setPayPrice(new BigDecimal(map.get("endNum").toString()));
                                        newPrice -=new Double(map.get("endNum").toString());
                                        userFlowing.setEndPrice(new BigDecimal(newPrice));
                                        userFlowing.setRemark("用户下注");
                                        userFlowingService.save(userFlowing);
                                    }

                                    //期数奖金池金额修改
                                    LambdaUpdateChainWrapper<PrizeRecord> lambdaUpdateChainWrapper = new LambdaUpdateChainWrapper<>(prizeRecordMapper);
                                    boolean update = lambdaUpdateChainWrapper.eq(PrizeRecord::getRecordId, prizeRecordOne.getRecordId())
                                            .set(PrizeRecord::getJackpotPrice, prizeRecordOne.getJackpotPrice() + endNum)
                                            .set(PrizeRecord::getRemainingPrice, prizeRecordOne.getJackpotPrice() + endNum)
                                            .set(PrizeRecord::getUpdateTime, DateUtil.date()).update();



                                    if (pumpRecordInfo == null) {
                                        //记录代理盘投入的总金额
                                        PumpRecord pumpRecord = new PumpRecord();
                                        pumpRecord.setCreateTime(DateUtil.date());
                                        pumpRecord.setAgentId(agentInfo.getId());
                                        pumpRecord.setAgentName(agentInfo.getAgentName());
                                        pumpRecord.setPeriod(prizeRecordOne.getPeriod());
                                        pumpRecord.setRoom(room);
                                        pumpRecord.setSumPrice(new BigDecimal(endNum));
                                        pumpRecordService.save(pumpRecord);
                                    } else {
                                        LambdaUpdateChainWrapper<PumpRecord> lambdaUpdatePumpRecord = new LambdaUpdateChainWrapper<>(pumpRecordMapper);
                                        lambdaUpdatePumpRecord.eq(PumpRecord::getPeriod, prizeRecordOne.getPeriod())
                                                .eq(PumpRecord::getRoom, room)
                                                .set(PumpRecord::getSumPrice, pumpRecordInfo.getSumPrice().add(new BigDecimal(endNum)))
                                                .set(PumpRecord::getUpdateTime, DateUtil.date()).update();
                                    }

                                    //修改用户余额
                                    LambdaUpdateChainWrapper<WeixinUser> lambdaUpdateUserWrapper = new LambdaUpdateChainWrapper<>(weixinUserMapper);
                                    lambdaUpdateUserWrapper.eq(WeixinUser::getId, userId)
                                            .set(WeixinUser::getUpdateTime, DateUtil.date())
                                            .set(WeixinUser::getPrice, remainPrice).update();
                                    remainPrice = new Double(String.format("%.2f", remainPrice));
                                    sendMsg = "@" + userName + " 用" + endNum + " 剩" + remainPrice +" 粮草";

                                } else {
                                    sendMsg = "@" + userName + " 请稍等";
                                }
                            }
                        }else{
                            sendMsg="@"+userName+" 粮草不足";
                        }
                    }else if (endNum>0 && endNum<10){
                        sendMsg = "@" + userName + " 投注金额必须十元起步";
                    } else {
                        sendMsg="@"+userName+" 指令输入有误";
                    }

                }else if (msg.equals("撤单")) {
                    //上期时间+30秒
                    PrizeRecord maxPrizeRecordByPrizeTime = prizeRecordMapper.getMaxPrizeRecordByPrizeTime();
                    DateTime dateTime = DateUtil.offsetSecond(maxPrizeRecordByPrizeTime.getPrizeTime(), 30);
                    if (dateTime.getTime() > DateUtil.date().getTime() && DateUtil.date().getTime() <= maxPrizeRecordByPrizeTime.getPrizeTime().getTime()) {
                        BetRecord betRecord = new BetRecord();
                        betRecord.setWexinId(getUser(session).getNickname());
                        betRecord.setRoom(RoomForUser.get(session.getId()));
                        betRecord.setPeriod(prizeRecordOne.getPeriod());
                        //返回用户所有投注的金额
                        Double userAllBetRecordPrice = betRecordMapper.getUserAllBetRecordPrice(betRecord);
                        if (userAllBetRecordPrice != 0 && userAllBetRecordPrice != null) {
                            //查询用户信息

                            //修改用户余额
                            LambdaUpdateChainWrapper<WeixinUser> lambdaUpdateUserWrapper = new LambdaUpdateChainWrapper<>(weixinUserMapper);
                            lambdaUpdateUserWrapper.eq(WeixinUser::getId, weixinUser.getId())
                                    .set(WeixinUser::getUpdateTime, DateUtil.date())
                                    .set(WeixinUser::getPrice, weixinUser.getPrice() + userAllBetRecordPrice).update();

                            //删除用户投注记录
                            Long[] ids = betRecordMapper.getUserAllBetRecord(betRecord);
                            if (ids.length != 0) {
                                for (Long id : ids) {
                                    betRecordMapper.deleteThePeriodAllBetRecord(id);
                                }
                            }
                            //删除该期用户流水
                            UserFlowing userFlowing = new UserFlowing();
                            userFlowing.setWexinId(getUser(session).getNickname());
                            userFlowing.setRoom(RoomForUser.get(session.getId()));
                            userFlowing.setPeriod(prizeRecordOne.getPeriod());
                            userFlowingMapper.deleteAllFlowingForUser(userFlowing);

                            sendMsg = "@" + userName + " 撤单成功";
                        } else {
                            sendMsg = "@" + userName + " \"" + msg + "\" 指令无效,请在规定时间里下单";
                        }
                    } else {
                        sendMsg = "@" + userName + " \"" + msg + "\"不在时间范围内";
                    }
                }
            }else{
                LambdaQueryWrapper<PrizeRecord> wrapperPrizeRecord = new LambdaQueryWrapper();
                wrapperPrizeRecord.eq(PrizeRecord::getState, 1).isNotNull(PrizeRecord::getPrizeTime).select();
                PrizeRecord prizeRecordOne = prizeRecordService.getOne(wrapperPrizeRecord);

                if (!msg.equals("余额") && !msg.equals("查") && !msg.contains("上分") && !msg.contains("下分") && !msg.contains("流水") && !msg.contains("玩法")) {
                    try {
                        startStr = substring(msg, 0, 1);
                        middleStr = substring(msg, 1, 2);
                        endStr = substring(msg, 2);
                        startNum = Integer.valueOf(startStr).intValue();
                        endNum = Double.valueOf(endStr);
                    } catch (Exception e) {
                        sendMsg = "@" + userName + " 指令输入有误";
                        state = false;
                    }
                    if (state) {
                        if (startNum > 0 && startNum <= 8) {
                            if (middleStr.equals("球")) {
                                if (endNum > 0 && endNum >= 10) {
                                    //抽水金额多位小数
                                    //代理抽水金额
                                    endNum = new Double(String.format("%.2f", endNum));

                                    Double price = Double.valueOf(weixinUser.getPrice());
                                    if (endNum <= price) {
                                        if (prizeRecordOne.getSealingState() == 2) {
                                            sendMsg = "@" + userName + " " + msg + " 已封盘，请稍后再试";
                                        } else {
                                            LambdaQueryWrapper<AgentInfo> wrapperAgentInfo = new LambdaQueryWrapper();
                                            wrapperAgentInfo.eq(AgentInfo::getRoom, RoomForUser.get(session.getId())).select();
                                            AgentInfo agentInfo = agentInfoService.getOne(wrapperAgentInfo);
                                            LambdaQueryWrapper<PumpRecord> wrapperPumpRecord = new LambdaQueryWrapper();
                                            String room = RoomForUser.get(session.getId());
                                            wrapperPumpRecord.eq(PumpRecord::getRoom, room)
                                                    .eq(PumpRecord::getPeriod, prizeRecordOne.getPeriod()).select();
                                            PumpRecord pumpRecordInfo = pumpRecordService.getOne(wrapperPumpRecord);
                                            if (prizeRecordOne != null) {
                                                //下注记录
                                                Long userId = weixinUser.getId();
                                                String wexinId = weixinUser.getWexinId();
                                                String wexinName = weixinUser.getWexinName();
                                                Double remainPrice = price - endNum;
                                                BetRecord betRecord = new BetRecord();
                                                betRecord.setCommand(msg);
                                                betRecord.setCreateTime(DateUtil.date());
                                                betRecord.setPeriod(prizeRecordOne.getPeriod());
                                                betRecord.setPayPrice(endNum);
                                                betRecord.setRoom(RoomForUser.get(session.getId()));
                                                betRecord.setUserId(userId);
                                                betRecord.setPayNum(startNum);
                                                betRecord.setWexinId(wexinId);
                                                betRecord.setWexinName(wexinName);
                                                betRecordService.save(betRecord);

                                                //期数奖金池金额修改
                                                LambdaUpdateChainWrapper<PrizeRecord> lambdaUpdateChainWrapper = new LambdaUpdateChainWrapper<>(prizeRecordMapper);
                                                boolean update = lambdaUpdateChainWrapper.eq(PrizeRecord::getRecordId, prizeRecordOne.getRecordId())
                                                        .set(PrizeRecord::getJackpotPrice, prizeRecordOne.getJackpotPrice() + endNum)
                                                        .set(PrizeRecord::getRemainingPrice, prizeRecordOne.getJackpotPrice() + endNum)
                                                        .set(PrizeRecord::getUpdateTime, DateUtil.date()).update();

                                                //记录用户流水
                                                UserFlowing userFlowing = new UserFlowing();
                                                userFlowing.setCreateTime(DateUtil.date());
                                                userFlowing.setUserId(userId);
                                                userFlowing.setWexinId(wexinId);
                                                userFlowing.setWexinName(wexinName);
                                                userFlowing.setRoom(RoomForUser.get(session.getId()));
                                                userFlowing.setPeriod(prizeRecordOne.getPeriod());
                                                userFlowing.setPayType(1);
                                                userFlowing.setIsFlowing(1);
                                                userFlowing.setBetId(betRecord.getId());
                                                userFlowing.setStartPrice(new BigDecimal(price));
                                                userFlowing.setPayPrice(new BigDecimal(endNum));
                                                userFlowing.setEndPrice(new BigDecimal(remainPrice));
                                                userFlowing.setRemark("用户下注");
                                                userFlowingService.save(userFlowing);

                                                if (pumpRecordInfo == null) {
                                                    //记录代理盘投入的总金额
                                                    PumpRecord pumpRecord = new PumpRecord();
                                                    pumpRecord.setCreateTime(DateUtil.date());
                                                    pumpRecord.setAgentId(agentInfo.getId());
                                                    pumpRecord.setAgentName(agentInfo.getAgentName());
                                                    pumpRecord.setPeriod(prizeRecordOne.getPeriod());
                                                    pumpRecord.setRoom(RoomForUser.get(session.getId()));
                                                    pumpRecord.setSumPrice(new BigDecimal(endNum));
                                                    pumpRecordService.save(pumpRecord);
                                                } else {
                                                    LambdaUpdateChainWrapper<PumpRecord> lambdaUpdatePumpRecord = new LambdaUpdateChainWrapper<>(pumpRecordMapper);
                                                    lambdaUpdatePumpRecord.eq(PumpRecord::getPeriod, prizeRecordOne.getPeriod())
                                                            .eq(PumpRecord::getRoom, RoomForUser.get(session.getId()))
                                                            .set(PumpRecord::getSumPrice, pumpRecordInfo.getSumPrice().add(new BigDecimal(endNum)))
                                                            .set(PumpRecord::getUpdateTime, DateUtil.date()).update();
                                                }

                                                //修改用户余额
                                                LambdaUpdateChainWrapper<WeixinUser> lambdaUpdateUserWrapper = new LambdaUpdateChainWrapper<>(weixinUserMapper);
                                                lambdaUpdateUserWrapper.eq(WeixinUser::getId, userId)
                                                        .set(WeixinUser::getUpdateTime, DateUtil.date())
                                                        .set(WeixinUser::getPrice, remainPrice).update();
                                                remainPrice = new Double(String.format("%.2f", remainPrice));
                                                sendMsg = "@" + userName + " 用" + endNum + " 剩" + remainPrice + "粮草";

                                            } else {
                                                sendMsg = "@" + userName + " 请稍等";
                                            }
                                        }
                                    } else {
                                        sendMsg = "@" + userName + " ";
                                    }
                                } else if (endNum > 0 && endNum < 10) {
                                    sendMsg = "@" + userName + " 投注金额必须十元起步";
                                } else {
                                    sendMsg = "@" + userName + " 指令输入有误";
                                }
                            } else {
                                sendMsg = "@" + userName + " 指令输入有误";
                            }
                        } else {
                            sendMsg = "@" + userName + " 指令输入有误";
                        }
                    }
                } else if (msg.equals("撤单")) {
                    //上期时间+30秒
                    PrizeRecord maxPrizeRecordByPrizeTime = prizeRecordMapper.getMaxPrizeRecordByPrizeTime();
                    DateTime dateTime = DateUtil.offsetSecond(maxPrizeRecordByPrizeTime.getPrizeTime(), 30);
                    if (dateTime.getTime() > DateUtil.date().getTime() && DateUtil.date().getTime() <= maxPrizeRecordByPrizeTime.getPrizeTime().getTime()) {
                        BetRecord betRecord = new BetRecord();
                        betRecord.setWexinId(getUser(session).getNickname());
                        betRecord.setRoom(RoomForUser.get(session.getId()));
                        betRecord.setPeriod(prizeRecordOne.getPeriod());
                        //返回用户所有投注的金额
                        Double userAllBetRecordPrice = betRecordMapper.getUserAllBetRecordPrice(betRecord);
                        if (userAllBetRecordPrice != 0 && userAllBetRecordPrice != null) {
                            //查询用户信息

                            //修改用户余额
                            LambdaUpdateChainWrapper<WeixinUser> lambdaUpdateUserWrapper = new LambdaUpdateChainWrapper<>(weixinUserMapper);
                            lambdaUpdateUserWrapper.eq(WeixinUser::getId, weixinUser.getId())
                                    .set(WeixinUser::getUpdateTime, DateUtil.date())
                                    .set(WeixinUser::getPrice, weixinUser.getPrice() + userAllBetRecordPrice).update();

                            //删除用户投注记录
                            Long[] ids = betRecordMapper.getUserAllBetRecord(betRecord);
                            if (ids.length != 0) {
                                for (Long id : ids) {
                                    betRecordMapper.deleteThePeriodAllBetRecord(id);
                                }
                            }
                            //删除该期用户流水
                            UserFlowing userFlowing = new UserFlowing();
                            userFlowing.setWexinId(getUser(session).getNickname());
                            userFlowing.setRoom(RoomForUser.get(session.getId()));
                            userFlowing.setPeriod(prizeRecordOne.getPeriod());
                            userFlowingMapper.deleteAllFlowingForUser(userFlowing);

                            sendMsg = "@" + userName + " 撤单成功";
                        } else {
                            sendMsg = "@" + userName + " \"" + msg + "\" 指令无效,请在规定时间里下单";
                        }
                    } else {
                        sendMsg = "@" + userName + " \"" + msg + "\"不在时间范围内";
                    }
                }
            }
            if (msg.equals("余额") || msg.equals("查")) {
                double price = weixinUser.getPrice();
                sendMsg = "@" + userName + " 剩" + price +" 粮草";
            } else if (msg.contains("下分") || msg.contains("上分") || msg.contains("下") || msg.contains("上")) {
                boolean branch = true;
                String substring2 = msg.substring(2, msg.length());
                BigDecimal bigDecimal = new BigDecimal(0);
                try {
                    bigDecimal = new BigDecimal(substring2).setScale(2, RoundingMode.HALF_UP);
                    ;
                } catch (Exception e) {
                    branch = false;
                }
                if (branch) {
                    if (bigDecimal.compareTo(new BigDecimal(0)) >= 1) {
                        BigDecimal price = new BigDecimal(weixinUser.getPrice());
                        UpdownBranch updownBranch = new UpdownBranch();
                        updownBranch.setPrice(bigDecimal);
                        updownBranch.setCreateTime(DateUtil.date());
                        updownBranch.setWexinId(weixinUser.getWexinId());
                        updownBranch.setWexinName(weixinUser.getWexinName());
                        updownBranch.setRoom(RoomForUser.get(session.getId()));
                        updownBranch.setUserId(weixinUser.getId());
                        updownBranch.setAuditStatus(0);
                        if (msg.contains("下分") || msg.contains("下")) {
                            if (price.setScale(2, RoundingMode.HALF_UP).compareTo(bigDecimal) >= 0) {
                                updownBranch.setBranchType(2);
                                sendMsg = "@" + userName + " 请稍后";
                                updownBranch.setRoom(RoomForUser.get(session.getId()));
                                updownBranchService.save(updownBranch);
                            } else {
                                sendMsg = "@" + userName + " 下分 " + bigDecimal + " 失败，剩：" + new Double(String.format("%.2f", price)) +"粮草";
                            }
                        } else {
                            updownBranch.setBranchType(1);
                            sendMsg = "@" + userName + " 请稍后";
                            updownBranch.setRoom(RoomForUser.get(session.getId()));
                            updownBranchService.save(updownBranch);
                        }
                    } else if (msg.contains("下分") || msg.contains("下")) {
                        sendMsg = "@" + userName + " 操作失败，至少下分1，格式例如：\"下分1\"";
                    } else if (msg.contains("上分") || msg.contains("上")) {
                        sendMsg = "@" + userName + " 操作失败，至少上分1，格式例如：\"上分1\"";
                    }
                } else {
                    if (msg.equals("上分") || msg.contains("上")) {
                        sendMsg = "@" + userName + " 操作失败，至少上分1，格式例如：\"上分1\"";
                    } else {
                        sendMsg = "@" + userName + " 操作失败，至少下分1，格式例如：\"下分1\"";
                    }
                }
            } else if (msg.equals("流水")) {
                //今日支出流水总数
                //            QueryWrapper<UserFlowing> out_wrapper = new QueryWrapper<UserFlowing>();
                //            out_wrapper.eq("room", RoomForUser.get(session.getId()));
                //            out_wrapper.eq("wexin_id", getUser(session).getNickname());
                //            out_wrapper.eq("is_flowing", 1);
                //            out_wrapper.eq("pay_type", 1);
                //            out_wrapper.apply("create_time", "date_format (create_time,'%Y-%m-%d') >= date_format('" + DateUtil.date() + "','%Y-%m-%d')");
                //            out_wrapper.select("IFNULL(sum(pay_price),0) as total ");
                //            Map<String, Object> out_map = userFlowingService.getMap(out_wrapper);

                UserFlowing userFlowing = new UserFlowing();
                userFlowing.setWexinId(getUser(session).getNickname());
                userFlowing.setRoom(RoomForUser.get(session.getId()));
                //今日收入流水总数
                String out = userFlowingMapper.getOut(userFlowing);
                String allOut =userFlowingMapper.getAll(userFlowing);
                String count =userFlowingMapper.getAllCount(userFlowing);
                Double total = new Double(out);
                Double allTotal= new Double(allOut);

                //            QueryWrapper<UserFlowing> int_wrapper = new QueryWrapper<UserFlowing>();
                //            int_wrapper.eq("room", RoomForUser.get(session.getId()));
                //            int_wrapper.eq("wexin_id", getUser(session).getNickname());
                //            int_wrapper.eq("is_flowing", 1);
                //            int_wrapper.eq("pay_type", 1);
                //            int_wrapper.apply("create_time", "date_format (create_time,'%Y-%m-%d') >= date_format('" + DateUtil.date() + "','%Y-%m-%d')");
                //            int_wrapper.select("IFNULL(sum(pay_price),0) as total ");
                //            Map<String, Object> int_map = userFlowingService.getMap(int_wrapper);
                //
                //            //今日流水
                //            double v = new Double(int_map.get("total").toString()) - new Double(out_map.get("total").toString());
                sendMsg = "@" + userName + "  累计流水 ："+allTotal+ "\n"+"，盈亏：" + total+"，期数："+count;
            }else if(msg.contains("玩法")){
                Map<String,String> rootResultOne = new HashMap<>();
                MsgRecord msgRecordOne = new MsgRecord();
                rootResultOne.put("type","img");
                msgRecordOne.setType(2);
                msgRecordOne.setMsg("http://admin.ballnicethis.xyz/prod-api/profile/upload/2021/08/04/975dfc5a-073d-4cdf-a152-97c1c6009026.jpg");
                rootResultOne.put("msg","http://admin.ballnicethis.xyz/prod-api/profile/upload/2021/08/04/975dfc5a-073d-4cdf-a152-97c1c6009026.jpg");
                rootResultOne.put("sendUser","机器人");
                rootResultOne.put("shake","");
                msgRecordOne.setRoomId(RoomForUser.get(session.getId()));
                msgRecordOne.setWexinName("机器人");
                msgRecordOne.setCreateTime(DateUtil.date());


                sendMsg = "@" + userName + "玩法";
                msgRecord.setMsg(sendMsg);
                msgRecordService.save(msgRecord);
                msgRecordService.save(msgRecordOne);
                rootResult.put("type", "msg");
                rootResult.put("msg", sendMsg);
                rootResult.put("sendUser", "机器人");
                rootResult.put("shake", "");
                if(RoomForUser.get(session.getId()) !=null && MyWebSocket.UserForRoom.get(RoomForUser.get(session.getId())) != null){
                    sendMessagesAll(MyWebSocket.UserForRoom.get(RoomForUser.get(session.getId())), gson.toJson(rootResult));
                    sendMessagesAll(MyWebSocket.UserForRoom.get(RoomForUser.get(session.getId())), gson.toJson(rootResultOne));
                }
                return;
            }
            msgRecord.setMsg(sendMsg);
            msgRecordService.save(msgRecord);
            rootResult.put("type", "msg");
            rootResult.put("msg", sendMsg);
            rootResult.put("sendUser", "机器人");
            rootResult.put("shake", "");
            if(RoomForUser.get(session.getId()) !=null && MyWebSocket.UserForRoom.get(RoomForUser.get(session.getId())) != null){
                sendMessagesAll(MyWebSocket.UserForRoom.get(RoomForUser.get(session.getId())), gson.toJson(rootResult));
            }
        }else{
            String sendMsg="请求无效该房间已关闭游戏";
            MsgRecord msgRecord = new MsgRecord();
            msgRecord.setRoomId(RoomForUser.get(session.getId()));
            msgRecord.setWexinName("机器人");
            msgRecord.setCreateTime(DateUtil.date());
            msgRecord.setType(1);
            msgRecord.setMsg(sendMsg);
            msgRecordService.save(msgRecord);
            rootResult.put("type", "msg");
            rootResult.put("msg", sendMsg);
            rootResult.put("sendUser", "机器人");
            rootResult.put("shake", "");
            if(RoomForUser.get(session.getId()) !=null && MyWebSocket.UserForRoom.get(RoomForUser.get(session.getId())) != null){
                sendMessagesAll(MyWebSocket.UserForRoom.get(RoomForUser.get(session.getId())), gson.toJson(rootResult));
            }
        }
    }

    public void rootSendMessageOne(String msg,String userName,String wexinId,String room){
        Map<String,String> rootResult = new HashMap<>();
        boolean state=true;
        MsgRecord msgRecord = new MsgRecord();
        msgRecord.setRoomId(room);
        msgRecord.setWexinName("机器人");
        msgRecord.setCreateTime(DateUtil.date());
        msgRecord.setType(1);
        String startStr="";
        String middleStr ="";
        String sendMsg="";
        String endStr="";
        int startNum =0;
        Double endNum =0.00;
        LambdaQueryWrapper<PrizeRecord> wrapperPrizeRecord = new LambdaQueryWrapper();
        wrapperPrizeRecord.eq(PrizeRecord::getState,1).isNotNull(PrizeRecord::getPrizeTime).select();
        PrizeRecord prizeRecordOne = prizeRecordService.getOne(wrapperPrizeRecord);
        if (!msg.contains("上分") && !msg.contains("下分")) {
            try {
                startStr= substring(msg, 0, 1);
                middleStr = substring(msg, 1, 2);
                endStr = substring(msg, 2);
                startNum =Integer.valueOf(startStr).intValue();
                endNum =Double.valueOf(endStr);
            }catch (Exception e){
                sendMsg="@"+userName+" 指令输入有误";
                state=false;
            }
            if(state){
                if (startNum>0 && startNum<=8) {
                    if (middleStr.equals("球")) {
                        if (endNum>0 && endNum>=10) {
                            //抽水金额多位小数
                            //代理抽水金额
                            endNum= new Double(String.format("%.2f",endNum));
                            LambdaQueryWrapper<WeixinUser> wrapper = new LambdaQueryWrapper();
                            wrapper.eq(WeixinUser::getWexinId,wexinId)
                                    .eq(WeixinUser::getRoom,room).select();
                            WeixinUser weixinUser = weixinUserService.getOne(wrapper);
                            Double price = Double.valueOf(weixinUser.getPrice());
                            if (endNum<=price) {
                                if (prizeRecordOne.getSealingState()==2) {
                                    sendMsg="@"+userName+" "+msg +" 已封盘，请稍后再试";
                                }else {
                                    LambdaQueryWrapper<AgentInfo> wrapperAgentInfo = new LambdaQueryWrapper();
                                    wrapperAgentInfo.eq(AgentInfo::getRoom,room).select();
                                    AgentInfo agentInfo = agentInfoService.getOne(wrapperAgentInfo);
                                    LambdaQueryWrapper<PumpRecord> wrapperPumpRecord = new LambdaQueryWrapper();
                                    wrapperPumpRecord.eq(PumpRecord::getRoom,room)
                                            .eq(PumpRecord::getPeriod,prizeRecordOne.getPeriod()).select();
                                    PumpRecord pumpRecordInfo = pumpRecordService.getOne(wrapperPumpRecord);
                                    if (prizeRecordOne != null) {
                                        //下注记录
                                        Long userId = weixinUser.getId();
                                        String wexinName = weixinUser.getWexinName();
                                        Double remainPrice = price - endNum;
                                        BetRecord betRecord = new BetRecord();
                                        betRecord.setCommand(msg);
                                        betRecord.setCreateTime(DateUtil.date());
                                        betRecord.setPeriod(prizeRecordOne.getPeriod());
                                        betRecord.setPayPrice(endNum);
                                        betRecord.setRoom(room);
                                        betRecord.setUserId(userId);
                                        betRecord.setPayNum(startNum);
                                        betRecord.setWexinId(wexinId);
                                        betRecord.setWexinName(wexinName);
                                        betRecordService.save(betRecord);

                                        //期数奖金池金额修改
                                        LambdaUpdateChainWrapper<PrizeRecord> lambdaUpdateChainWrapper = new LambdaUpdateChainWrapper<>(prizeRecordMapper);
                                        boolean update = lambdaUpdateChainWrapper.eq(PrizeRecord::getRecordId, prizeRecordOne.getRecordId())
                                                .set(PrizeRecord::getJackpotPrice, prizeRecordOne.getJackpotPrice() + endNum)
                                                .set(PrizeRecord::getRemainingPrice, prizeRecordOne.getJackpotPrice() + endNum)
                                                .set(PrizeRecord::getUpdateTime, DateUtil.date()).update();

                                        //记录用户流水
                                        UserFlowing userFlowing = new UserFlowing();
                                        userFlowing.setCreateTime(DateUtil.date());
                                        userFlowing.setUserId(userId);
                                        userFlowing.setWexinId(wexinId);
                                        userFlowing.setWexinName(wexinName);
                                        userFlowing.setRoom(room);
                                        userFlowing.setPeriod(prizeRecordOne.getPeriod());
                                        userFlowing.setPayType(1);
                                        userFlowing.setIsFlowing(1);
                                        userFlowing.setBetId(betRecord.getId());
                                        userFlowing.setStartPrice(new BigDecimal(price));
                                        userFlowing.setPayPrice(new BigDecimal(endNum));
                                        userFlowing.setEndPrice(new BigDecimal(remainPrice));
                                        userFlowing.setRemark("用户下注");
                                        userFlowingService.save(userFlowing);

                                        if (pumpRecordInfo == null) {
                                            //记录代理盘投入的总金额
                                            PumpRecord pumpRecord = new PumpRecord();
                                            pumpRecord.setCreateTime(DateUtil.date());
                                            pumpRecord.setAgentId(agentInfo.getId());
                                            pumpRecord.setAgentName(agentInfo.getAgentName());
                                            pumpRecord.setPeriod(prizeRecordOne.getPeriod());
                                            pumpRecord.setRoom(room);
                                            pumpRecord.setSumPrice(new BigDecimal(endNum));
                                            pumpRecordService.save(pumpRecord);
                                        } else {
                                            LambdaUpdateChainWrapper<PumpRecord> lambdaUpdatePumpRecord = new LambdaUpdateChainWrapper<>(pumpRecordMapper);
                                            lambdaUpdatePumpRecord.eq(PumpRecord::getPeriod, prizeRecordOne.getPeriod())
                                                    .eq(PumpRecord::getRoom, room)
                                                    .set(PumpRecord::getSumPrice, pumpRecordInfo.getSumPrice().add(new BigDecimal(endNum)))
                                                    .set(PumpRecord::getUpdateTime, DateUtil.date()).update();
                                        }

                                        //修改用户余额
                                        LambdaUpdateChainWrapper<WeixinUser> lambdaUpdateUserWrapper = new LambdaUpdateChainWrapper<>(weixinUserMapper);
                                        lambdaUpdateUserWrapper.eq(WeixinUser::getId, userId)
                                                .set(WeixinUser::getUpdateTime, DateUtil.date())
                                                .set(WeixinUser::getPrice, remainPrice).update();
                                        remainPrice = new Double(String.format("%.2f", remainPrice));
                                        sendMsg = "@" + userName + " 用" + endNum + " 剩" + remainPrice +" 粮草";

                                    } else {
                                        sendMsg = "@" + userName + " 请稍等";
                                    }
                                }
                            }else{
                                sendMsg="@"+userName+" 粮草不足";
                            }
                        }else if (endNum>0 && endNum<10){
                            sendMsg = "@" + userName + " 投注金额必须十元起步";
                        } else {
                            sendMsg="@"+userName+" 指令输入有误";
                        }
                    }else {
                        sendMsg="@"+userName+" 指令输入有误";
                    }
                }else {
                    sendMsg="@"+userName+" 指令输入有误";
                }
            }
        }else if(msg.contains("下分") || msg.contains("")){
            boolean branch=true;
            String substring2 = msg.substring(2,msg.length());
            BigDecimal bigDecimal=new BigDecimal(0);
            try {
                bigDecimal = new BigDecimal(substring2).setScale(2, RoundingMode.HALF_UP);;
            }catch (Exception e){
                branch=false;
            }
            if (branch) {
                if (bigDecimal.compareTo(new BigDecimal(0))>=1) {
                    LambdaQueryWrapper<WeixinUser> wrapper = new LambdaQueryWrapper();
                    wrapper.eq(WeixinUser::getWexinId,wexinId)
                            .eq(WeixinUser::getRoom,room)
                            .select();
                    WeixinUser weixinUser = weixinUserService.getOne(wrapper);
                    BigDecimal price = new BigDecimal(weixinUser.getPrice());
                    UpdownBranch updownBranch = new UpdownBranch();
                    updownBranch.setPrice(bigDecimal);
                    updownBranch.setCreateTime(DateUtil.date());
                    updownBranch.setWexinId(weixinUser.getWexinId());
                    updownBranch.setWexinName(weixinUser.getWexinName());
                    updownBranch.setRoom(room);
                    updownBranch.setUserId(weixinUser.getId());
                    updownBranch.setAuditStatus(0);
                    if(msg.contains("下分")){
                        if (price.setScale(2, RoundingMode.HALF_UP).compareTo(bigDecimal)>=0) {
                            updownBranch.setBranchType(2);
                            sendMsg="@"+userName+" 请稍后";
                            updownBranch.setRoom(room);
                            updownBranchService.save(updownBranch);
                        }else{
                            sendMsg="@"+userName+" 下分 "+bigDecimal+" 失败，剩："+new Double(String.format("%.2f", price))+" 粮草";
                        }
                    }else{
                        updownBranch.setBranchType(1);
                        sendMsg="@"+userName+" 请稍后";
                        updownBranch.setRoom(room);
                        updownBranchService.save(updownBranch);
                    }
                }else if(msg.contains("下分")){
                    sendMsg="@"+userName+" 操作失败，至少下分1，格式例如：\"下分1\"";
                }else if(msg.contains("上分")){
                    sendMsg="@"+userName+" 操作失败，至少上分1，格式例如：\"上分1\"";
                }
            }
        }
        msgRecord.setMsg(sendMsg);
        msgRecordService.save(msgRecord);
        rootResult.put("type","msg");
        rootResult.put("msg",sendMsg);
        rootResult.put("sendUser","机器人");
        rootResult.put("shake","");
        if(MyWebSocket.UserForRoom.get(room) != null){
            sendMessagesAll(MyWebSocket.UserForRoom.get(room), gson.toJson(rootResult));
        }
    }

    public void rootSendMessageTwo(String msg,String userName,String wexinId,String room){
        Map<String,String> rootResult = new HashMap<>();
        boolean state=true;
        MsgRecord msgRecord = new MsgRecord();
        msgRecord.setRoomId(room);
        msgRecord.setWexinName("机器人");
        msgRecord.setCreateTime(DateUtil.date());
        msgRecord.setType(1);
        String startStr="";
        String middleStr ="";
        String sendMsg="";
        String endStr="";
        int startNum =0;
        Double endNum =0.00;
        LambdaQueryWrapper<PrizeRecord> wrapperPrizeRecord = new LambdaQueryWrapper();
        wrapperPrizeRecord.eq(PrizeRecord::getState,1).isNotNull(PrizeRecord::getPrizeTime).select();
        PrizeRecord prizeRecordOne = prizeRecordService.getOne(wrapperPrizeRecord);
        if (!msg.contains("上分") && !msg.contains("下分")) {
            try {
                String command="";
                if (msg.contains("番")) {
                    command="番";
                    startNum= msg.indexOf("番");
                    String strOne=msg.substring(startNum,msg.length());
                    String str = strOne.replaceAll(command, "");
                    endNum = Double.valueOf(str);
                }else if(msg.contains("角")){
                    command="角";
                    startNum= msg.indexOf("角");
                    String strOne=msg.substring(startNum,msg.length());
                    String str = strOne.replaceAll(command, "");
                    endNum = Double.valueOf(str);
                }else if(msg.contains("车")){
                    command="车";
                    startNum= msg.indexOf("车");
                    String strOne=msg.substring(startNum,msg.length());
                    String str = strOne.replaceAll(command, "");
                    endNum = Double.valueOf(str);
                }else if(msg.contains("念")){
                    command="/";
                    startNum= msg.indexOf(command);
                    String strOne=msg.substring(startNum,msg.length());
                    String str = strOne.replaceAll(command, "");
                    endNum = Double.valueOf(str);
                }else if(msg.contains("堂")){
                    command="堂";
                    startNum= msg.indexOf("堂");
                    String strOne=msg.substring(startNum,msg.length());
                    String str = strOne.replaceAll(command, "");
                    endNum = Double.valueOf(str);
                }else if(msg.contains("通")){
                    command="/";
                    startNum= msg.indexOf(command);
                    String strOne=msg.substring(startNum,msg.length());
                    String str = strOne.replaceAll(command, "");
                    endNum = Double.valueOf(str);
                }else if(msg.contains("单")){
                    command="单";
                    startNum= msg.indexOf("单");
                    String strOne=msg.substring(startNum,msg.length());
                    String str = strOne.replaceAll(command, "");
                    endNum = Double.valueOf(str);
                }else if(msg.contains("双")){
                    command="双";
                    startNum= msg.indexOf("双");
                    String strOne=msg.substring(startNum,msg.length());
                    String str = strOne.replaceAll(command, "");
                    endNum = Double.valueOf(str);
                }else if(msg.contains("大")){
                    command="大";
                    startNum= msg.indexOf("大");
                    String strOne=msg.substring(startNum,msg.length());
                    String str = strOne.replaceAll(command, "");
                    endNum = Double.valueOf(str);
                }else if(msg.contains("小")){
                    command="小";
                    startNum= msg.indexOf("小");
                    String strOne=msg.substring(startNum,msg.length());
                    String str = strOne.replaceAll(command, "");
                    endNum = Double.valueOf(str);
                }else if(msg.contains("特")){
                    command="特";
                    startNum= msg.indexOf("特");
                    String strOne=msg.substring(startNum,msg.length());
                    String str = strOne.replaceAll(command, "");
                    endNum = Double.valueOf(str);
                    endNum=endNum*msg.split("/").length;
                }

            }catch (Exception e){
                sendMsg="@"+userName+" 指令输入有误";
                state=false;
            }
            if(state){
                if (endNum>0 && endNum>=10) {
                    //抽水金额多位小数
                    //代理抽水金额
                    endNum= new Double(String.format("%.2f",endNum));
                    LambdaQueryWrapper<WeixinUser> wrapper = new LambdaQueryWrapper();
                    wrapper.eq(WeixinUser::getWexinId,wexinId)
                            .eq(WeixinUser::getRoom,room).select();
                    WeixinUser weixinUser = weixinUserService.getOne(wrapper);
                    Double price = Double.valueOf(weixinUser.getPrice());
                    if (endNum<=price) {
                        if (prizeRecordOne.getSealingState()==2) {
                            sendMsg="@"+userName+" "+msg +" 已封盘，请稍后再试";
                        }else {
                            LambdaQueryWrapper<AgentInfo> wrapperAgentInfo = new LambdaQueryWrapper();
                            wrapperAgentInfo.eq(AgentInfo::getRoom,room).select();
                            AgentInfo agentInfo = agentInfoService.getOne(wrapperAgentInfo);
                            LambdaQueryWrapper<PumpRecord> wrapperPumpRecord = new LambdaQueryWrapper();
                            wrapperPumpRecord.eq(PumpRecord::getRoom,room)
                                    .eq(PumpRecord::getPeriod,prizeRecordOne.getPeriod()).last("limit 1").select();
                            PumpRecord pumpRecordInfo = pumpRecordService.getOne(wrapperPumpRecord);
                            if (prizeRecordOne != null) {
                                //下注记录
                                Long userId = weixinUser.getId();
                                String wexinName = weixinUser.getWexinName();
                                Double remainPrice = price - endNum;
                                BetRecord betRecord = new BetRecord();
                                betRecord.setCommand(msg);
                                betRecord.setCreateTime(DateUtil.date());
                                betRecord.setPeriod(prizeRecordOne.getPeriod());
                                betRecord.setPayPrice(endNum);
                                betRecord.setRoom(room);
                                betRecord.setUserId(userId);
                                betRecord.setPayNum(startNum);
                                betRecord.setWexinId(wexinId);
                                betRecord.setWexinName(wexinName);
                                betRecordService.save(betRecord);

                                //期数奖金池金额修改
                                LambdaUpdateChainWrapper<PrizeRecord> lambdaUpdateChainWrapper = new LambdaUpdateChainWrapper<>(prizeRecordMapper);
                                boolean update = lambdaUpdateChainWrapper.eq(PrizeRecord::getRecordId, prizeRecordOne.getRecordId())
                                        .set(PrizeRecord::getJackpotPrice, prizeRecordOne.getJackpotPrice() + endNum)
                                        .set(PrizeRecord::getRemainingPrice, prizeRecordOne.getJackpotPrice() + endNum)
                                        .set(PrizeRecord::getUpdateTime, DateUtil.date()).update();

                                //记录用户流水
//                                UserFlowing userFlowing = new UserFlowing();
//                                userFlowing.setCreateTime(DateUtil.date());
//                                userFlowing.setUserId(userId);
//                                userFlowing.setWexinId(wexinId);
//                                userFlowing.setWexinName(wexinName);
//                                userFlowing.setRoom(room);
//                                userFlowing.setPeriod(prizeRecordOne.getPeriod());
//                                userFlowing.setPayType(1);
//                                userFlowing.setIsFlowing(1);
//                                userFlowing.setBetId(betRecord.getId());
//                                userFlowing.setStartPrice(new BigDecimal(price));
//                                userFlowing.setPayPrice(new BigDecimal(endNum));
//                                userFlowing.setEndPrice(new BigDecimal(remainPrice));
//                                userFlowing.setRemark("用户下注");
//                                userFlowingService.save(userFlowing);

//                                if (pumpRecordInfo == null) {
//                                    //记录代理盘投入的总金额
//                                    PumpRecord pumpRecord = new PumpRecord();
//                                    pumpRecord.setCreateTime(DateUtil.date());
//                                    pumpRecord.setAgentId(agentInfo.getId());
//                                    pumpRecord.setAgentName(agentInfo.getAgentName());
//                                    pumpRecord.setPeriod(prizeRecordOne.getPeriod());
//                                    pumpRecord.setRoom(room);
//                                    pumpRecord.setSumPrice(new BigDecimal(endNum));
//                                    pumpRecordService.save(pumpRecord);
//                                } else {
//                                    LambdaUpdateChainWrapper<PumpRecord> lambdaUpdatePumpRecord = new LambdaUpdateChainWrapper<>(pumpRecordMapper);
//                                    lambdaUpdatePumpRecord.eq(PumpRecord::getPeriod, prizeRecordOne.getPeriod())
//                                            .eq(PumpRecord::getRoom, room)
//                                            .set(PumpRecord::getSumPrice, pumpRecordInfo.getSumPrice().add(new BigDecimal(endNum)))
//                                            .set(PumpRecord::getUpdateTime, DateUtil.date()).update();
//                                }

                                //修改用户余额
                                LambdaUpdateChainWrapper<WeixinUser> lambdaUpdateUserWrapper = new LambdaUpdateChainWrapper<>(weixinUserMapper);
                                lambdaUpdateUserWrapper.eq(WeixinUser::getId, userId)
                                        .set(WeixinUser::getUpdateTime, DateUtil.date())
                                        .set(WeixinUser::getPrice, remainPrice).update();
                                remainPrice = new Double(String.format("%.2f", remainPrice));
                                sendMsg = "@" + userName + " 用" + endNum + " 剩" + remainPrice +" 粮草";

                            } else {
                                sendMsg = "@" + userName + " 请稍等";
                            }
                        }
                    }else{
                        sendMsg="@"+userName+" 粮草不足";
                    }
                }else if (endNum>0 && endNum<10){
                    sendMsg = "@" + userName + " 投注金额必须十元起步";
                } else {
                    sendMsg="@"+userName+" 指令输入有误";
                }

            }
        }else if(msg.contains("下分") || msg.contains("")){
            boolean branch=true;
            String substring2 = msg.substring(2,msg.length());
            BigDecimal bigDecimal=new BigDecimal(0);
            try {
                bigDecimal = new BigDecimal(substring2).setScale(2, RoundingMode.HALF_UP);;
            }catch (Exception e){
                branch=false;
            }
            if (branch) {
                if (bigDecimal.compareTo(new BigDecimal(0))>=1) {
                    LambdaQueryWrapper<WeixinUser> wrapper = new LambdaQueryWrapper();
                    wrapper.eq(WeixinUser::getWexinId,wexinId)
                            .eq(WeixinUser::getRoom,room)
                            .select();
                    WeixinUser weixinUser = weixinUserService.getOne(wrapper);
                    BigDecimal price = new BigDecimal(weixinUser.getPrice());
                    UpdownBranch updownBranch = new UpdownBranch();
                    updownBranch.setPrice(bigDecimal);
                    updownBranch.setCreateTime(DateUtil.date());
                    updownBranch.setWexinId(weixinUser.getWexinId());
                    updownBranch.setWexinName(weixinUser.getWexinName());
                    updownBranch.setRoom(room);
                    updownBranch.setUserId(weixinUser.getId());
                    updownBranch.setAuditStatus(0);
                    if(msg.contains("下分")){
                        if (price.setScale(2, RoundingMode.HALF_UP).compareTo(bigDecimal)>=0) {
                            updownBranch.setBranchType(2);
                            sendMsg="@"+userName+" 请稍后";
                            updownBranch.setRoom(room);
                            updownBranchService.save(updownBranch);
                        }else{
                            sendMsg="@"+userName+" 下分 "+bigDecimal+" 失败，剩："+new Double(String.format("%.2f", price));
                        }
                    }else{
                        updownBranch.setBranchType(1);
                        sendMsg="@"+userName+" 请稍后";
                        updownBranch.setRoom(room);
                        updownBranchService.save(updownBranch);
                    }
                }else if(msg.contains("下分")){
                    sendMsg="@"+userName+" 操作失败，至少下分1，格式例如：\"下分1\"";
                }else if(msg.contains("上分")){
                    sendMsg="@"+userName+" 操作失败，至少上分1，格式例如：\"上分1\"";
                }
            }
        }
        msgRecord.setMsg(sendMsg);
        msgRecordService.save(msgRecord);
        rootResult.put("type","msg");
        rootResult.put("msg",sendMsg);
        rootResult.put("sendUser","机器人");
        rootResult.put("shake","");
        if(MyWebSocket.UserForRoom.get(room) != null){
            sendMessagesAll(MyWebSocket.UserForRoom.get(room), gson.toJson(rootResult));
        }
    }

    public static String substring(String str, int startNum, int endNum){
        String substring = str.substring(startNum,endNum);
        return substring;
    }


    public String substring(String str,int num){
        String substring = str.substring(num);
        return substring;
    }


    /**
     * 连接发生错误时的调用方法
     * @param session
     * @param error
     */
    /**
     * 连接发生错误时的调用方法
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.debug("---------------------与{}的连接发生错误---------------------",session.getId());
        subOnlineCount();
        CopyOnWriteArraySet<User> users = getUsers(session);
        if (users!=null){
            String nick = "某人";
            String weixinId="";
            for (User user : users) {
                if (user.getId().equals(session.getId())){
                    weixinId = user.getNickname();
                    LambdaQueryWrapper<WeixinUser> wrapper = new LambdaQueryWrapper();
                    wrapper.eq(WeixinUser::getWexinId,weixinId).last("limit 1");
                    WeixinUser weixinUser = weixinUserService.getOne(wrapper);
                    nick =weixinUser.getWexinName();
                }
            }
            Map<String,String> result = new HashMap<>();
            result.put("type","init");
//            result.put("msg",nick+"离开房间");
//            result.put("sendUser","系统消息");
            sendMessagesOther(users,gson.toJson(result));
            User closeUser = getUser(session);
            users.remove(closeUser);
            if (users.size() == 0){
                String room = RoomForUser.get(session.getId());
                UserForRoom.remove(room);
                PwdForRoom.remove(room);
            }
            RoomForUser.remove(session.getId());
        }
        error.printStackTrace();
    }


    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * 获得在线人数
     * @return
     */
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        MyWebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        MyWebSocket.onlineCount--;
    }


    /**
     * 根据当前用户的session获得他所在房间的所有用户
     * @param session
     * @return
     */
    public static CopyOnWriteArraySet<User> getUsers(Session session){
        String room = RoomForUser.get(session.getId());
        CopyOnWriteArraySet<User> users = UserForRoom.get(room);
        return users;
    }

    private User getUser(Session session){
        String room = RoomForUser.get(session.getId());
        CopyOnWriteArraySet<User> users = UserForRoom.get(room);
        for (User user : users){
            if (session.getId().equals(user.getId())){
                return user;
            }
        }
        return null;
    }

    /**
     * 给某个房间的所有人发送消息
     * @param users
     * @param message
     */
    public void sendMessagesAll(CopyOnWriteArraySet<User> users, String message){
        //群发消息
        for (User item : users) {
            try {
                item.getWebSocket().sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 给某个房间除自己外发送消息
     * @param users
     * @param message
     */
    public void sendRoomMessagesOther(CopyOnWriteArraySet<User> users, String message){
            //群发消息
            for (User item : users) {
                if (item.getWebSocket() != this) {
                    try {
                        item.getWebSocket().sendMessage(message);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    }

    public void noUserSendOther(String msg,String userName,String wexinId,String room){
        try {
            if(new User().getWebSocket()!=null){
                new User().getWebSocket().sendMessage(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            rootSendMessageOne(msg,userName,wexinId,room);
            logger.info("noUserSendOther---rootSendMessageOne");
        }
    }

    public void noUserSendOtherOne(String msg,String userName,String wexinId,String room){
        try {
            if(new User().getWebSocket()!=null){
                new User().getWebSocket().sendMessage(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            rootSendMessageTwo(msg,userName,wexinId,room);
            logger.info("noUserSendOther---rootSendMessageOne");
        }
    }

    private void sendMessagesOther(CopyOnWriteArraySet<User> users, String message){
        //群发消息
        for (User item : users) {
            if (item.getWebSocket() != this){
                try {
                    item.getWebSocket().sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 给某个房间除自己外发送消息
     * @param users
     * @param message
     */
    private void sendMessagesAll(CopyOnWriteArraySet<User> users, String message, String shiel){
        List<String> shiels = Arrays.asList(shiel.split(","));
        //群发消息
        for (User item : users) {
            if (item.getWebSocket() != this && !shiels.contains(item.getId())){
                try {
                    item.getWebSocket().sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
